package ch.areion.areionapp.communication;

import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import ch.areion.areionapp.Main;
import ch.areion.areionapp.R;
import ch.areion.areionapp.core.Controller;
import ch.areion.areionapp.io.BoxNumber;
import ch.areion.common.message.Module;
import ch.areion.common.message.Type;
import ch.areion.common.message.Version;

import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ActHTTP extends IOIOActivity {
	private TextView text_fullname;
	public TextView text_response;
	private EditText edit_url;
	private Button but_send;

	private String s_url;
	private String s_team;
	private String s_scan;
	private static Controller contr;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http);

		text_fullname = (TextView) findViewById(R.id.text_fullurl);
		text_response = (TextView) findViewById(R.id.test_response);
		edit_url = (EditText) findViewById(R.id.editText_URL);
		but_send = (Button) findViewById(R.id.button_send);

		text_response.setTextColor(Color.RED);

		Intent i = getIntent();
		// Receiving the Data
		if ((s_scan = i.getStringExtra("scan")) != null) {
			edit_url.setText(s_scan);
			request();
		} else {
			edit_url.setText(R.string.standard_url);
		}

		but_send.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				request();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.http, menu);
		return true;
	}

	public void request() {
		String full_url;

		if (edit_url.getText().length() > 0) {
			s_url = edit_url.getText().toString();
		} else {
			s_url = getString(R.string.standard_url, edit_url.getText());
		}

		s_team = getString(R.string.team);
		full_url = s_url + s_team;

		text_fullname.setText(full_url);

		// try downloading
		Monitor.getInstance().add(Version.V01, Type.INFO, Module.COMMUNICATION,
				"Requested", full_url);
		DownloadWebPageTask task = new DownloadWebPageTask();
		task.execute(new String[] { full_url });

	}

	private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = "";
			for (String url : urls) {
				DefaultHttpClient client = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(url);
				try {
					HttpResponse execute = client.execute(httpGet);
					InputStream content = execute.getEntity().getContent();

					BufferedReader buffer = new BufferedReader(
							new InputStreamReader(content));
					String s = "";
					while ((s = buffer.readLine()) != null) {
						response += s;
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return response;
		}

		@Override
		protected void onPostExecute(String result) {
			text_response.setText("Park-Nr. " + result);
			Controller.setBoxNumber(result);

			int boxNumber = 0;
			try {
				boxNumber = Integer.parseInt(result);
			} catch (Exception ex) {
				Monitor.getInstance()
						.add(Version.V01, Type.ERROR, Module.PERIPHERY,
								"Unable to identify box number " + ex);
			}

			// play sound
			Monitor.getInstance().add(Version.V01, Type.INFO, Module.PERIPHERY,
					"Playing sound " + result);
		//	MediaPlayer p = null;
			try {
				switch (boxNumber) {
				case 1:
				default:
					Controller.getIO().setDisplayBoxnumber(BoxNumber.N1);
					//p = MediaPlayer.create(getBaseContext(), R.raw.box1);

					break;
				case 2:

					Controller.getIO().setDisplayBoxnumber(BoxNumber.N2);
					//p = MediaPlayer.create(getBaseContext(), R.raw.box2);
					break;
				case 3:
					Controller.getIO().setDisplayBoxnumber(BoxNumber.N3);
					//p = MediaPlayer.create(getBaseContext(), R.raw.box3);
					break;
				case 4:
					Controller.getIO().setDisplayBoxnumber(BoxNumber.N4);
					//p = MediaPlayer.create(getBaseContext(), R.raw.box4);
					break;
				case 5:
					Controller.getIO().setDisplayBoxnumber(BoxNumber.N5);
					//p = MediaPlayer.create(getBaseContext(), R.raw.box5);
					break;
				}
			} catch (ConnectionLostException e) {
				Monitor.getInstance().add(Version.V01, Type.ERROR,
						Module.PERIPHERY, "ConnectionLost: " + e);

			}
			//if (p != null)

				try {
					//p.start();
					contr = Main.getControllerInstance();
					contr.startAfterQRCODE();
				} catch (ConnectionLostException e) {
					Monitor.getInstance().add(Version.V01, Type.ERROR,
							Module.PERIPHERY, "ConnectionLost: " + e);
				} catch (InterruptedException e) {
					Monitor.getInstance().add(Version.V01, Type.ERROR,
							Module.PERIPHERY, "InterruptedException: " + e);
				}
		}

	}

	@Override
	protected IOIOLooper createIOIOLooper() {
		return Main.getControllerInstance();
	}

//	public void onBackPressed() {
//		super.onBackPressed();
//	}

}
